package com.lzk.filter;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 局部过滤器，实现gatewayfilter，ordered
 * 需要和配置类一起使用
 */
public class RequestTimeFilter implements GatewayFilter, Ordered {

    //创建日志器，进行日志打印
    private static final Logger log = LoggerFactory.getLogger(RequestTimeFilter.class);

    /**
     *
     * @param exchange 服务网络交换器，存放着重要的请求-响应属性、请求实例和响应实例等等，类似于请求上下文对象
     * @param chain Gateway的filter调用链对象
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求地址,打印日志
        String path = exchange.getRequest().getURI().getPath();
        log.info("RequestTimeFilter执行,请求路径为：{}",path);
        //2.存入请求开始的时间
        exchange.getAttributes().put("startTime",System.currentTimeMillis());
        //3.执行完成
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    // 开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    // 结束时间
                    Long endTime = (System.currentTimeMillis() - startTime);
                    // 打印当前请求耗时
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );

    }
    /**
     * 执行时机，默认为0，0为最高顺序
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
